# handle_post_broadcast.py - Handle queue requests to post via non-twitter apis.
# Copyright 2010 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import post_data
import random
import traceback
import yaml

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

try:
    from google.appengine.api.taskqueue import Task
except:
    from google.appengine.api.labs.taskqueue import Task

class PostBroadcastWorker(webapp.RequestHandler):
    def broadcast(self, url, queue, params):
        task = Task(url=url, method='POST', params=params)
        task.add(queue)

    def post(self):
        dgr_yaml_path = self.request.get('dgr-yaml-path')
        post_data = self.request.get('post-data')
        emotions = self.request.get('emotions')
        if(dgr_yaml_path and post_data and emotions):
            try:
                config = yaml.safe_load(file(dgr_yaml_path, 'r'))
                params={'dgr-yaml-path': dgr_yaml_path,
                        'post-data': post_data,
                        'emotions': emotions}
                if 'friendfeed_nickname' in config and \
                        config['friendfeed_nickname'] != '':
                    self.broadcast('/post-friendfeed', 'post-queue', 
                                   params)
                if 'posterous_username' in config and \
                        config['posterous_username'] != '':
                    self.broadcast('/post-posterous', 'post-queue', 
                                   params)
                if 'tumblr_blog' in config and \
                        config['tumblr_blog'] != '':
                    self.broadcast('/post-tumblr', 'post-queue', 
                                   params)
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/post-broadcast', PostBroadcastWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
